package com.example.administrator.testproject.flagTextview;

import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.RectF;
import android.text.style.ReplacementSpan;

public class RadiusBackgroundSpan extends ReplacementSpan {
    private int mSize;
    private Integer mStrokeColor;
    private int mRadius;
    private float textSize;
    private boolean isFull;

    /**
     * @param strokeColor 边线颜色
     * @param radius     圆角半径
     */
    public RadiusBackgroundSpan(Integer strokeColor,float size, boolean full, int radius) {
        mStrokeColor = strokeColor;
        mRadius = radius;
        textSize = size;
        isFull = full;
    }

    @Override
    public int getSize(Paint paint, CharSequence text, int start, int end, Paint.FontMetricsInt fm) {
        paint.setTextSize(textSize);
        mSize = (int) (paint.measureText(text, start, end) + 2 * mRadius);
        return mSize;
    }

    @Override
    public void draw(Canvas canvas, CharSequence text, int start, int end, float x, int top, int y, int bottom, Paint paint) {
        int color = paint.getColor();
        float strokeWidth = paint.getStrokeWidth();
        paint.setColor(mStrokeColor == null ? color : mStrokeColor);//设置背景颜色
        paint.setAntiAlias(true);// 设置画笔的锯齿效果
        paint.setStrokeWidth(strokeWidth + 3);
        paint.setStyle(isFull ? Paint.Style.FILL : Paint.Style.STROKE);
        paint.setTextSize(textSize);
//        canvas.drawLine(0f,y,200f,y,paint);
//        Log.e("Tag",paint.ascent()+"=="+top+"="+paint.descent());
//        RectF oval = new RectF(x, y + paint.ascent(), x + mSize, y + paint.descent());
        Paint.FontMetrics a = paint.getFontMetrics();
        float descent = a.descent;
        RectF oval = new RectF(x, top + a.descent, x + mSize, bottom - a.descent);
        //设置文字背景矩形，x为span其实左上角相对整个TextView的x值，y为span左上角相对整个View的y值。paint.ascent()获得文字上边缘，paint.descent()获得文字下边缘
        canvas.drawRoundRect(oval, mRadius, mRadius, paint);//绘制圆角矩形，第二个参数是x半径，第三个参数是y半径
        paint.setColor(isFull? Color.WHITE : (mStrokeColor==null?color:mStrokeColor));//恢复画笔的文字颜色
        paint.setStrokeWidth(strokeWidth);
//        canvas.drawText(text, start, end, x + mRadius, y, paint);//绘制文字
        canvas.drawText(text, start, end, x + mRadius, (bottom - top) / 2 + (paint.getTextSize() - descent) / 2, paint);//绘制文字
    }
}